package com.mine.controller;

import com.mine.pojo.Meal;
import com.mine.pojo.Order;
import com.mine.pojo.User;
import com.mine.service.OrderService;
import com.mine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    //*我的收藏
    @GetMapping("user_favorites")
    public String user_favorites(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if(user==null){ //如果找不到用户，转到登录页
            model.addAttribute("msg","请先登录");
            return "login";
        }
        if(!"0".equals(user.getCollect())){
            List<Meal> mealList = userService.queryCollectMealByUser(user);
            model.addAttribute("mealList",mealList);
        }
        return "user/user_favorites";
    }


    //*展示个人主页信息
    @GetMapping("/user_center")
    public String userCenter(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) { //如果找不到用户，转到登录页
            model.addAttribute("msg", "请先登录");
            return "login";
        }
        List<Order> orderList = orderService.queryOrderByUserId(user.getUser_id());
        model.addAttribute("orderSize",orderList.size());
        return "user/user_center";
    }

    //*修改个人信息
    @GetMapping("/user/update")
    public String updateUser() {
        return "user/user_update";
    }
    @PostMapping("/user/update")
    public String updateUser(User user, Model model, HttpSession session) {
        User user0 = (User) session.getAttribute("user");
        List<Order> orderList = orderService.queryOrderByUserId(user0.getUser_id());
        model.addAttribute("orderSize",orderList.size());
        User u = userService.getUserByName(user.getUsername());
        if(u != null && !user0.getUsername().equals(u.getUsername())){
            model.addAttribute("msg_update", "用户名已被使用，请换一个用户名");
            return "user/user_center";
        }
        User user1 = userService.updateUser(user);
        model.addAttribute("msg_update", "修改个人信息成功");
        session.setAttribute("user",user1);
        return "user/user_center";
    }

}
